package com.medibooking.gwt.client.util;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.datepicker.client.CalendarUtil;

/**
 * 
 * @author joaomiguel.pereira@gmail.com
 * 
 *         An utility class to manipulate dates
 * 
 */
public class CalendarUtils {

    /**
     * Get the date of the last monday of the current week
     * 
     * @return A date representing the monday of the current week
     */
    public static Date getLastMondayDate() {
        return getLastMondayDate(new Date());
    }

    /**
     * Get the date of the last monday of the current week
     * 
     * @return A date representing the monday of the current week
     */
    public static Date getLastMondayDate(Date referenceDate) {
        Date date = new Date(referenceDate.getTime());
        CalendarUtil.addDaysToDate(date, -1 * (getCurrentDayInWeek(date)));
        return date;
    }

    /**
     * Return the current day in week. 0 - Monday, 7 Sunday
     * 
     * @return
     */
    public static int getCurrentDayInWeek(Date date) {

        int day = date.getDay();
        if (day == 0) {
            day = 6;
        } else {
            day -= 1;
        }
        return day;
    }

    /**
     * Convert an double value representing the number of hours to minutes. For
     * example: 0.0 - 0 minutes 0.5 - 30 minutes 1.0 - 60 minutes 1.5 - 90
     * minutes 0.25 - 15 minutes
     * 
     * @param hours
     * @return
     */
    public static int toMinutes(double hours) {

        return (int) Math.round(60 * hours);
    }

    /**
     * How many slots and hour has if the size of the slot is give
     * 
     * @param slotSize
     * @return
     */
    public static int getSlotsInAnHour(double slotSize) {
        return (int) Math.round(60 / (slotSize * 60));

    }

    public static boolean isStartHour(double hours) {
        return hours % 1 == 0;

    }

    public static Date getDateWithAddedDays(Date date, int numberOfDays) {
        // Create a new date
        Date newDate = new Date(date.getTime());
        CalendarUtil.addDaysToDate(newDate, numberOfDays);
        return newDate;
    }

    public static int getDifferenceInDays(Date startDate, Date endDate) {

        long start = startDate.getTime();
        long end = endDate.getTime();
        float diff = (end - start) / 1000 / 60 / 60 / 23;
        return (int) diff;
    }
}
